function I = selePolyPoints(xg,yg,hfig)
%selePolyPoints - Interactive choice of points included in a polygon 
%
%       I = selePolyPoints(xg,yg,hfig)
%
% Let [xg,yg] be a 2D set of points represented in the figure hfig. 
% This function allows the choice of the points inside a polygon 
% interactively chosen by using the mouse. The polygon vertices and
% sides are drawn as the selection is carried out. As the selection is 
% completed by clicking on the return button, the polygon is deleted.
% The output logical variable I, which has the same size of xg and yg,
% is true in the points inside the polygon and false otherwise.
% If hfig is undefined or empty, the default choice hfig = gcf is used.

% G. Teza, 2022.

if nargin < 3
    hfig = gcf;
end

figure(hfig);
hold on;

nok = false;
x = [];
y = [];
nprog = 1;
while ~nok
    [xs,ys,butt] = ginput(1);
    x = [x; xs]; %#ok<*AGROW>
    y = [y; ys];
    if nprog > 1
        delete(hl);
    end
    hl=line(x,y,'Color','red','LineStyle','--','LineWidth',2,...
        'Marker','o','HandleVisibility','off');
    nprog = nprog+1;
    if isempty(butt)
        nok = true;
        delete(hl);
    end
end

hold off;

I = inpolygon(xg,yg,x,y);